package com.dolphin.serviceorder.service.impl;

import com.dolphin.common.constant.CommonStatusEnum;
import com.dolphin.common.dto.ResponseResult;
import com.dolphin.common.request.DriverGrabRequest;
import com.dolphin.serviceorder.service.GrabService;
import com.dolphin.serviceorder.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service("grabByRedisDiyService")
@Slf4j
public class GrabByRedisDiyServiceImpl implements GrabService {

    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    RenewRedisLock renewRedisLock;
    @Override
    public ResponseResult grab(DriverGrabRequest driverGrabRequest) {
        ResponseResult grab = null;

        String driverId = driverGrabRequest.getDriverId()+"";
        String orderId = driverGrabRequest.getOrderId()+"";

        //设置加锁的key和过期时间
         Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(orderId, driverId, 20, TimeUnit.SECONDS);
        renewRedisLock.renewRedisLock(orderId, driverId, 20);
        if (aBoolean) {
            log.info("开始锁redis diy");
            grab = orderInfoService.grab(driverGrabRequest);
            log.info("释放锁redis diy");
            stringRedisTemplate.delete(orderId);
        } else {
            grab = ResponseResult.fail(CommonStatusEnum.ORDER_GRABING.getCode(),CommonStatusEnum.ORDER_GRABING.getValue());
        }
        return grab;

    }


}
